package org.achao.controller;

import org.achao.task.TaskRunner;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RestController
@RequestMapping("/task")
public class TaskController {

    private final ExecutorService executorService = Executors.newCachedThreadPool();

    @PostMapping("/start-task")
    public ResponseEntity<String> startTask(@RequestParam String userName, @RequestParam String executionTime) {
        try {
            // 解析用户传递的时间
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date scheduledTime = dateFormat.parse(executionTime);

            // 计算任务开始时间与当前时间的时间差，以毫秒为单位
            long delay = scheduledTime.getTime() - System.currentTimeMillis();

            if (delay < 0) {
                return ResponseEntity.badRequest().body("传递的时间已过期");
            }

            // 在指定的时间后执行任务
            executorService.submit(new TaskRunner(userName, delay));

            return ResponseEntity.ok("任务将在 " + executionTime + " 开始执行");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("任务启动失败");
        }
    }

}
